'use strict';
/**
 * @fileoverview pvp地图
 * @author sundbcn@gmail.com (sun debing)
 */

var mongoose = require('mongoose');
var moment = require('moment');
var _ = require('lodash');
var async = require('async');
var constantUtil = require('../util/constantUtil');
var pvpMgr = require('../mgr/pvpMgr');
var dataApi = require('../libs/dataApi');
var mapPlayerItemSchema = require('./map/mapPlayerItemSchema');
var mapBossItemSchema = require('./map/mapBossItemSchema');
var mapEventItemSchema = require('./map/mapEventItemSchema');
var pvpBlackItemSchema = require('./pvp/pvpBlackItemSchema.js');
var pvpConf = require('../config/pvpConf');
var buildType = require('../consts/buildType');
var buildConf = require('../config/buildConf');
var pvpService = require('../services/pvpService');

// 初始化
var _initMapRoad = function () {
    var road_list = [];
    dataApi.pvp_start.each(function (value, key) {
        road_list.push(key);
    });
    return road_list;
};

// 初始化位置
var _initCurrentPos = function () {
    return 312;
};

/**
 * 初始免费更新对手次数
 */
var _getFreeChangeRival = function () {
    return constantUtil.value('pvp_fresh_free_time');
};

/**
 * map功能
 */
var pvpSchema = new mongoose.Schema({
    // 角色id
    role_id: {
        type: Number,
        required: true,
        unique: true,
        index: true
    },

    // 已开启的路块列表
    road_list: {
        type: [Number],
        default: _initMapRoad
    },

    // boss列表
    boss_list: [mapBossItemSchema],

    // 随机事件
    event_list: [mapEventItemSchema],

    // pvp玩家列表
    player_list: [mapPlayerItemSchema],

    // 黑名单列表(角色ID)
    black_list: [pvpBlackItemSchema],

    // 最后添加黑名单数据时间
    last_add_black_list: {
        type: Number,
        default: 0
    },

    // 对手ID
    rival_Id: {
        type: Number,
        default: 0
    },

    // 对手即时金币
    rival_gold: {
        type: Number,
        default: 0
    },

    // 对手即时食物
    rival_food: {
        type: Number,
        default: 0
    },

    // 累计星数
    star_count: {
        type: Number,
        default: 0
    },

    // 下次开宝箱时间
    open_honor_box_tm: {
        type: Number,
        default: 0
    },

    // 剩余免费更换对手次数
    free_change_rival: {
        type: Number,
        default: _getFreeChangeRival
    },
});

pvpSchema.pre('save', function (next) {
    this.increment();
    if (!this.isNew && !!this.isModified()) {
        this.pushModify();
    }
    next();
});

/**
 * 重置免费更换对手次数
 */
pvpSchema.methods.resetFreeChangeRival = function () {
    this.free_change_rival = _getFreeChangeRival();
};

/**
 * 减少免费更换对手次数
 * @return {[type]} [description]
 */
pvpSchema.methods.decFreeChangeRivalCnt = function () {
    if (this.free_change_rival < 1) {
        return false;
    }
    this.free_change_rival--;
    return true;
};

/**
 * 刷新boss
 * @return {[type]} [description]
 */
pvpSchema.methods.refreshBoss = function (hero_lv) {
    var self = this;
    var pvp_boss_all_conf = _.sample(dataApi.pvp_boss.all());

    // 清空boss数据
    this.boss_list = [];

    _.each(pvp_boss_all_conf, function (pvp_boss_conf) {
        var road_id = pvp_boss_conf.coordinate_id;

        if (!self.isRoadOpen(hero_lv, road_id)) {
            return;
        }
        var pvp_boss_des_conf = _.sample(dataApi.pvp_boss_des.all());
        self.boss_list.push({
            road_id: road_id,
            boss_type: pvp_boss_des_conf.id
        });
    });
};

/**
 * 刷新随机事件
 * @return {[type]} [description]
 */
pvpSchema.methods.refreshEvent = function (job_type, nexus_lv, hero_lv) {
    var self = this;
    var event_vocation_conf = dataApi.event_vocation.findById(job_type);
    var event_all_conf = [];
    _.each(event_vocation_conf, function (event_vocation_item) {
        if (event_vocation_item.castle_lvl == nexus_lv) {
            event_all_conf.push(event_vocation_item);
        }
    });

    if (event_all_conf.length <= 0) {
        return;
    }

    // 清空boss数据
    this.event_list = [];

    var sample_event_coordinate = _.sample(dataApi.event_coordinate.all());
    _.each(sample_event_coordinate, function (coordinate_item) {
        var road_id = coordinate_item.coordinate_id;

        if (!self.isRoadOpen(hero_lv, road_id)) {
            return;
        }
        var event_conf = _.sample(event_all_conf);
        self.event_list.push({
            road_id: road_id,
            event_type: event_conf.event_id
        });
    });
};

/**
 * 获取boss
 * @param  {[type]} road_id [description]
 * @return {[type]}         [description]
 */
pvpSchema.methods.getRoadBoss = function (road_id) {
    var road_boss = null;
    _.some(this.boss_list, function (boss_item) {
        if (boss_item.road_id == road_id) {
            road_boss = boss_item;
        }
    });
    return road_boss;
};

/**
 * 添加军功宝箱星数
 * @param  {[type]} star [description]
 * @return {[type]}         [description]
 */
pvpSchema.methods.addHonorBoxStar = function (add_star) {
    var honor_box_need_star = constantUtil.value('honor_box_need_star');
    if (this.star_count >= honor_box_need_star) {
        // 已满星，不处理
        return;
    }

    var now_tm = moment().unix();
    if (this.open_honor_box_tm > now_tm) {
        // CD中不加星
        return;
    }

    add_star = +add_star;
    this.star_count += add_star;
    if (this.star_count > honor_box_need_star) {
        this.star_count = honor_box_need_star;
    }
};

// 按地块ID查找
pvpSchema.methods.getRoadPlayer = function (road_id) {
    var road_player = null;
    _.some(this.player_list, function (player_item) {
        if (player_item.road_id == road_id) {
            road_player = player_item;
        }
    });
    return road_player;
};

// 按角色ID查找
pvpSchema.methods.findByRoleId = function (role_id) {
    var road_player = null;
    _.some(this.player_list, function (player_item) {
        if (player_item.role_id == role_id) {
            road_player = player_item;
        }
    });
    return road_player;
};

// 在黑名单中查找指定玩家
pvpSchema.methods.findBlack = function (find_role_id) {
    return _.find(this.black_list, {
        role_id: find_role_id
    });
};

pvpSchema.methods.getRoadEvent = function (road_id) {
    var road_event = null;
    _.some(this.event_list, function (event_item) {
        if (event_item.road_id == road_id) {
            road_event = event_item;
        }
    });
    return road_event;
};

pvpSchema.methods.removeRoadEvent = function (road_event) {
    this.event_list.pull(road_event);
};

pvpSchema.methods.removeRoadBoss = function (road_boss) {
    this.boss_list.pull(road_boss);
};

pvpSchema.methods.removeRoadPlayer = function (road_player) {
    this.player_list.pull(road_player);
};

// 从黑名单中删除指定玩家
pvpSchema.methods.removeFromBlackList = function (role_id) {
    var black_player = _.find(this.black_list, {
        role_id: role_id
    });

    if (!!black_player) {
        this.black_list.pull(black_player);
        return true;
    }
    return false;
};

// 将玩家添加到黑名单中
pvpSchema.methods.addToBlackList = function (role_id) {
    // 将旧的攻打记录从黑名单中删除（如果存在）
    this.removeFromBlackList(role_id);

    // 控制黑名单长度
    var pvp_black_limit = constantUtil.value('pvp_black_limit');
    if (_.size(this.black_list) >= pvp_black_limit) {
        this.removeFromBlackList(this.black_list[0].role_id);
    }

    var add_time = moment().unix();
    this.black_list.push({
        role_id: role_id,
        add_time: add_time
    });

    this.last_add_black_list = add_time;
};

pvpSchema.methods.addRoadPlayer = function (player) {
    if (this.getRoadPlayer(player.road_id)) {
        return false;
    }
    this.player_list.push(player);
    this.markModified('player_list');
    return true;
};

/**
 * 是否地块开启
 * @param  {[type]}  road_id [description]
 * @return {Boolean}         [description]
 */
pvpSchema.methods.isRoadOpen = function (hero_lv, road_id) {
    var open_road_list = pvpService.getOpenRoadList(hero_lv);
    var is_open = false;
    _.some(open_road_list, function (road_item) {
        if (road_item.coordinate_id == road_id) {
            is_open = true;
            return true;
        }
    });
    return is_open;
};

pvpSchema.methods.getPlayerRoleIdList = function () {
    var role_id_list = [];
    _.each(this.player_list, function (player_item) {
        role_id_list.push(player_item.role_id);
    });
    return role_id_list;
};

/**
 * 获取修改
 * @return {[type]} [description]
 */
pvpSchema.methods.getLastChange = function () {
    return this.toJSON();
};

/**
 * 推送给用户
 * @return {[type]} [description]
 */
pvpSchema.methods.push = function () {
    this.pushModify();
};

pvpSchema.methods.pushModify = function () {
    pvpMgr.sendPvpBlackChanged(
        this.role_id,
        this.getLastChange(),
        function (err, fails) {
            if (err) {
                console.error('send map message error: %j, fail ids: %j', err, fails);
                return;
            }
        }
    );
};

if (!pvpSchema.options.toJSON) {
    pvpSchema.options.toJSON = {};
}
/* jshint unused:false */
pvpSchema.options.toJSON.transform = function (doc, ret) {
    delete ret._id;
    delete ret.__v;
    delete ret.last_refresh_boss_time;
};

mongoose.model('Pvp', pvpSchema);
